<?php
/**
* Apps的类
*/

require_once(dirname(__FILE__).'/../../config/UCConfApps.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibPDOFactory.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibStat.php');
require_once(dirname(__FILE__).'/../../../op/interface/SdoAppStore.php');
require_once(dirname(__FILE__).'/../relation/UCModRelation.php');

class UCModApps
{	
	//定义变量
	private static $instance; //用于构建类的singleton模式参数
    private $_user_id;
    private $_user_apps=array();
	private $_cache;
	public	$error_no = 0;
	
	//定义数组
	public 	$arr_system_apps;
	public 	$arr_recommend_apps;
	public	$arr_user_apps;	
	public	$arr_all_apps;
		
	
    public function __construct()
    {
        $this->_user_id = Yii::app()->user->getId();
		$this->_cache = new UCLibCache('apps');
		$pdo_store = UCLibPDOFactory::getPDO('store',$this->_user_id,"apps2dbconfig");

		//初始化系统的应用数组
		$list = $this->_cache->read('APPS_STORE_SYSTEM_ALL');
		if($list === false || !is_array($list))
		{
			$list  = $pdo_store->query_with_prepare("select * from $pdo_store->database.$pdo_store->table where issystem=1 order by position asc");
			if(false === $list){
				$this->_errno =  UCConfApps::APP_ERROR_DB_READ;
				return false;
			}elseif(!is_array($list)){ 
				$list = array();
			}
			$this->_cache->write('APPS_STORE_SYSTEM_ALL', $list);
		}
		$this->arr_system_apps = $list;

		//初始化所有的应用数组
		$list = $this->_cache->read('APPS_STORE_ALL');
		if($list === false || !is_array($list))
		{
			$list  = $pdo_store->query_with_prepare("select * from $pdo_store->database.$pdo_store->table");
			if(false === $list){
				$this->_errno =  UCConfApps::APP_ERROR_DB_READ;
				return false;
			}elseif(!is_array($list)){ 
				$list = array();
			}

			foreach ($list as $app){
				$this->arr_all_apps[$app['id']] = $app;
			}

			$this->_cache->write('APPS_STORE_ALL', $this->arr_all_apps);
		}else{
			$this->arr_all_apps = $list;
		}
		
		//初始化推荐的应用数组
		$list = $this->_cache->read('APPS_STORE_RECOMMEND');
		if($list === false || !is_array($list))
		{
			$pdo_store = UCLibPDOFactory::getPDO('store',$this->_user_id,"apps2dbconfig");	
			$list  = $pdo_store->query_with_prepare("select * from $pdo_store->database.$pdo_store->table where isrecommend = 1 order by position asc");
			if(false === $list){
				$this->_errno =  UCConfApps::APP_ERROR_DB_READ;
				return false;
			}elseif(!is_array($list)){ 
				$list = array();
			}

			$this->_cache->write('APPS_STORE_RECOMMEND', $list);
		}
		$this->arr_recommend_apps = $list;
		$this->arr_user_apps = $this->getUserApp();		
    }
    
    
    //测试函数
    function testme(){
    	print_r($this->arr_recommend_apps);
    	echo "<hr />" ;
    }
	
	/**
	 * 析构函数
	 *
	 */
	function __destruct()
	{
		$this->_cache->close();
	}
	
	//获取用户APP列表
	//参数:数量,是否返回未添加的推荐应用
	//返回:应用的数组.
	function getUserApp($count=0,$withRecommendApps=0,$dopage=1){
		if(empty($this->_user_id)){
			$list = $this->arr_system_apps;
		}else{
			//从MC中获取
			$list = $this->appsGetMc();
			//MC中获取失败,去数据库->API中获取,并更新MC
			//if(empty($list)){
			if(1){	//从数据库中获取
				$list = $this->appsGetDb();
				//DB获取失败
				if(empty($list)){
				//if(1){//调试:跳过DB
					//组合成用户默认APP
					$list = $this->arr_system_apps;
					$this->appsBatchAddDb($list);
				}
				$this->appsUpdateMc($list);	
			}
		}
		
		//后续处理:是否返回未添加的推荐应用
		if($withRecommendApps){
			//处理推荐应用
			$recomend_apps = $this->_dealRecommendApps($list);
			//合并应用
			$user_apps = array_merge($list,$recomend_apps);
		}else{
			$user_apps = $list;
		}
		
		if(!empty($count))
		{
			$user_apps_list = array_slice($user_apps,0,$count);
		}else{
			$user_apps_list = $user_apps;
		}

		if($dopage){
			return array_chunk($user_apps_list,18);
		}else{
			return $user_apps_list;
		}
		
	}
	//添加用户应用
	function addUserApp($app_ids)
	{
		if(empty($app_ids))
		{
			$this->error_no = UCConfApps::APP_ERROR_PARAM;
			return false;
		}
		
		$user_appids = $this->_getUserAppids;
		
		foreach($app_ids as $value)
		{
			if(!in_array($value,$user_appids)){
				$tmparr[] = $value;
			}
		}
		if(!empty($tmparr))
		{
			if(!$this->appsBatchAddDb($this->getBatchAppInfo($tmparr))){
				$this->error_no = UCConfApps::APP_ERROR_DB_WRITE;
				return false;
			}else{
				$this->appsUpdateMc($this->appsGetDb());
			}
		}
		//用户应用添加统计
		UCLibStat::statex(UCConfStat::STAT_APP_INSTALL,$this->_user_id);
		return true;
	}
	
	function getUserPlayedAppids(){
		$user_appids = array();
		$pdo = UCLibPDOFactory::getPDO('logs',$this->_user_id,'apps2dbconfig');
		//获取用户玩儿过的应用id
		$list  = $pdo->query_with_prepare("select * from $pdo->database.$pdo->table where user_id = ?",array($this->_user_id));
		if(empty($list)){
			return array();
		}
		for($i=0;$i<count($list);$i++)
		{
			$user_appids[] = $list[$i]['app_id'];
		}
		return $user_appids;
		
	}
	
	function updateUserPlayedAppLog($appid){
		if(empty($appid)){
			return false;
		}		
		$pdo = UCLibPDOFactory::getPDO('logs',$this->_user_id,'apps2dbconfig');
		//判断用户是否玩过该应用
		$list  = $pdo->query_with_prepare("select * from $pdo->database.$pdo->table where user_id= ? and app_id = ?",array($this->_user_id,$appid));
		if(!empty($list)){
			$pdo->query_with_prepare("update $pdo->database.$pdo->table set lastplay=?  where user_id= ? and app_id = ?",array(time(),$this->_user_id,$appid));
		}else{
			$pdo->query_with_prepare("insert into $pdo->database.$pdo->table (user_id,app_id,lastplay) values (?,?,?)",array($this->_user_id,$appid,time()));
		}
			
	}
	
	
	
	//获取用户APPS的IDs
	function _getUserAppids($user_apps = array()){
		if(empty($user_apps)){
			$user_apps = $this->getUserApp(0,0,0);
		}
		for($i=0;$i<count($user_apps);$i++)
		{
			$user_appids[] = $user_apps[$i]['id'];
		}
		if(empty($user_appids)){
			$user_appids=array();
		}
		return $user_appids;		
	}
	
	//获取系统APPS的IDs
	function _getUCAppids(){
		return $this->arr_system_apps;		
	}
	
	//处理推荐应用
	//返回用户未加的推荐应用array
	function _dealRecommendApps($user_apps){
		$user_appids = $this->_getUserAppids($user_apps);
		
		foreach($this->arr_recommend_apps as $value)
		{
			if(!in_array($value['id'],$user_appids)){
				$tmparr[] = $value['id'];
			}
		}
		if(!empty($tmparr))
		{
			$tmparr_list = $this->getBatchAppInfo($tmparr);
			if(empty($tmparr_list)){
				return array();
			}
			return $tmparr_list;
		}else{
			return array();
		}
		
	}
	
	//批量添加到数据库
	function appsBatchAddDb($apps)
	{	
		//从数据库读现有的
		$p=count($this->appsGetDb());		
		foreach ($apps as $app){
			$p=$p+1;
			if(!$app['user_id']) $app['user_id'] = $this->_user_id;
			$app['position'] = $p;
			if(false === $this->appsAddDb($app)){
				return false;
			}
		}
		return true;
	}
	
	//添加到数据库,单条
	function appsAddDb($data)
	{
		$pdo = UCLibPDOFactory::getPDO('userapps',$this->_user_id,'apps2dbconfig');
		//判断该应用是否为用户应用
		$list  = $pdo->query_with_prepare("select * from $pdo->database.$pdo->table where user_id= ? and id= ? ",array($data['user_id'],$data['id']));
		if(!empty($list)){
			return false;
		}
		$data['userapps_id'] = $pdo -> gen_uuid();

		unset($data['issystem']);
		unset($data['isrecommend']);
		unset($data['icon_middle']);
		unset($data['icon_big']);		
		unset($data['icon_large']);
		
		$result  = $pdo -> insert($data);
		if(false === $result){
			return false;
		}
		return true;
	}
	//添加到MCache
	function appsAddMc($apps)
	{
		$mc_key= md5('uc_apps'.$this->_user_id);
		//$data = serialize($apps);
		if(!$this->_cache->write($mc_key, $apps)){
			$this->error_no = UCConfApps::APP_ERROR_MC_WRITE;
			return false;
		}		
		return true;
	}
	
	//更新数据库,主要用于更新排序
	function appsUpdateDb($condition,$fields)
	{
		if(empty($condition)){
			$this->_errno = UCConfApps::APP_ERROR_PARAM;
			return false;
		}
		$pdo = UCLibPDOFactory::getPDO('userapps',$this->_user_id,"apps2dbconfig");
		$update  = $pdo -> update($fields,$condition);
		if($update){			
			$list  = $pdo->query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? order by position asc",array($this->_user_id));
			//更新下MC
			$this->appsUpdateMc($list);
			return true;
		}else{	
			$this->_errno = UCConfApps::APP_ERROR_DB_WRITE;
			return false;
		}
		
	}
	//更新MC,读取数据库,然后更新到MC
	function appsUpdateMc($apps)
	{
		$mc_key= md5('uc_apps'.$this->_user_id);
		//$data = serialize($apps);
		if(!$this->_cache->write($mc_key, $apps)){
			$this->error_no = UCConfApps::APP_ERROR_MC_WRITE;
			return false;
		}
		return true;
	}
	//更新到API
	function appsUpdateApi($apps)
	{
		return true;
	}
	//读取数据库,条数
	function appsGetDb($start = 0,$limit = 1000)
	{
		$pdo = UCLibPDOFactory::getPDO('userapps',$this->_user_id,"apps2dbconfig");	
		$list  = $pdo->query_with_prepare("select * from $pdo->database.$pdo->table where user_id=? order by position asc limit ?,?",array($this->_user_id,$start,$limit));
		if(false === $list){
			$this->_errno =  UCConfApps::APP_ERROR_DB_READ;
			return false;
		//没有记录，则返回空数组
		}elseif(!is_array($list)){ 
			$list = array();
		}
		return $list;
	}
	//读取MC
	function appsGetMc()
	{
		$mc_key= md5('uc_apps'.$this->_user_id);
		//$data = serialize($apps);
		if(!$list=$this->_cache->read($mc_key, $apps)){
			$this->error_no = UCConfApps::APP_ERROR_MC_WRITE;
			return false;
		}		
		return $list;
	}
	//读取API
	function appsGetApi()
	{
		//读取到的appid如果不在系统定义中,那么取消之.
		return  $this->_fuckedupOtherApps(SdoAppStore::getUserApps($this->_user_id));
	}
	//删除DB内数据
	function appsDelDb($apps)
	{
		
		return true;
	}
	//删除MC缓存
	function appsDelMc($apps)
	{
		
		return true;
	}
	//删除API那边
	function appsDelApi($apps)
	{
		return true;
	}
	
	/**
     * 获取应用信息
     * @return array
     */
	function getAppInfo($appId)
	{
		$list = array();
		if(empty($this->arr_all_apps)){
			//初始化所有的应用数组			
			$pdo_store = UCLibPDOFactory::getPDO('store',$this->_user_id,"apps2dbconfig");
			$list  = $pdo_store->query_with_prepare("select * from $pdo_store->database.$pdo_store->table");
			foreach ($list as $app){
				$this->arr_all_apps[$app['id']] = $app;
			}
		}
		
		$app = $this->arr_all_apps[$appId];
		return $app;
	}
	/**
     * 批量获取应用信息
     * @return array
     */
	function getBatchAppInfo($appIds)
	{
		$uc_apps = array();
		if(is_array($appIds)){
			foreach($appIds as $key=>$appid){
				$uc_apps[$appid] = $this->getAppInfo($appid);
				}
		}

		return $uc_apps;
		
	}
	
	//更新排序
	function modAppSequence($ar_sequence)
	{
		if(empty($ar_sequence))
		{
			$this->error_no = UCConfApps::APP_ERROR_PARAM;
			return false;
		}		
		
		//这里循环+计数器
		$counter = 0;
		foreach ($ar_sequence as $value){
			$counter = $counter + 1;
			//更新数据库 $condition=array('user_id'=>$this->_user_id,'id'=>$value);
			$ret = $this->appsUpdateDb(array('user_id'=>$this->_user_id, 'id'=>$value), array('position'=>$counter));
		}
		return true;
	}
	
	/**
     * 获取应用的邀请链接
     * 
     * @param int	$appId
     * @param int	$inviterUid 邀请者uid
     * @param bool	$outer		是否是站外邀请
     * @return		string		应用不存在或无效时，返回空字符串，否则返回邀请链接，
     * 站外邀请链接将返回的url做为回跳参数加在注册链接后
     */

	function getAppInviteUrl($app_id,$outer=false)
	{
		if(empty($app_id))
		{
			$this->error_no = UCConfApps::APP_ERROR_PARAM;
			return false;
		}
		return UC_CONF_UC_DOMAIN."/invite?app_id=".$app_id;
	}
	
	/**
	 * 获取单个APP信息
	 * @param	int		$app_id	APPID
	 * @return	array			不存在返回NULL
	 *
	 */
	function getUserFriendsInApp($app_id)
	{
		return array();
	}
	
	
	
	/**
     * 判断用户是否对一个应用授权过
     *
     * @param	int		$app_id
     * @return	bool
     */
    function isUserApp($app_id)
    {
    	$pdo_logs = UCLibPDOFactory::getPDO('logs',$this->_user_id,"apps2dbconfig");
		//初始化应用
		$list  = $pdo_logs->query_with_prepare("select * from $pdo_logs->database.$pdo_logs->table where user_id=? and id=? order by lastplay desc",array($this->_user_id,$app_id));
		if(false === $list){
			$this->_errno =  UCConfApps::APP_ERROR_DB_READ;
			return false;
		//没有记录，则返回空数组
		}elseif(!is_array($list)){ 
			return false;
		}
		return true;
    }
	
	/**
	 * 获取用户邀请推荐APP
	 * @return	array			用户APP数组
	 *
	 */
	function getUserAppForInvite($count = 0)
	{	
		
		return $this->getUserRecentlyPlayedApps($this->_user_id, $count);
	}
	
    /**
     * 批量获取用户最近玩过的应用
     * 最多获取30个
     * @param array $uids 用户的uid数组 
     * @param integer $count 每个用户最近玩过应用返回的最大个数
     * @return array 以uid为键值的数组 array(uid => array( id => app_info_array, ...), ...)
     */
    function getUsersRecentlyPlayedApps($uids, $count = 0)
    {
        $ret = array();
        foreach ($uids as $uid) {
            $ret[$uid] = $this->getUserRecentlyPlayedApps($uid, $count);
        }
        return $ret;
    }

    /**
     * 获取一个用户最近玩过的应用
     *
     * @param integer $uid 用户id
     * @param integer $count 默认0, 返回个数， 0表示返回所有
     * @param boolean $innerGetSort 仅内部调用使用，用于获取排序规则
     * @return array
     */
    function getUserRecentlyPlayedApps($uid, $count = 0)
    {	
		if(!empty($count)){
			if($count>50) $count=50;
			$pdo_logs = UCLibPDOFactory::getPDO('logs',$this->_user_id,"apps2dbconfig");
			//初始化应用
			$list  = $pdo_logs->query_with_prepare("select id from $pdo_logs->database.$pdo_logs->table where user_id=? order by lastplay desc limit 0,?",array($uid,$count));
			if(false === $list){
				$this->_errno =  UCConfApps::APP_ERROR_DB_READ;
				return false;
			//没有记录，则返回空数组
			}elseif(!is_array($list)){ 
				return $list;
			}
			//取app数据
			foreach ($list as $value){
				$apps[$value['id']]	= $this->getAppInfo($value['id']);			
			}			
			return $apps;
		}
    }
	
	
    /**
     * 批量获取多个应用的最近使用用户
     *
     * @param array $appIds
     * @param integer $maxcount
     * @return array array( appId => array(uid, ...), ...)
     */
    public function getAppsUsers($appIds, $maxCount = 1000)
    {
        $ret = array();
        foreach ($appIds as $appId) {
            $ret[$appId] = $this->getAppUsers($appId, $maxCount);
        }
        return $ret;
    }
	
	
	//获取一个应用的最近使用用户
	//返回用户array(user_id)
    public function getAppUsers($appId, $maxCount = 1000)
    {
    	if(!empty($maxCount)){
			$pdo_logs = UCLibPDOFactory::getPDO('logs',$this->_user_id,"apps2dbconfig");
			//初始化应用
			$list  = $pdo_logs->query_with_prepare("select user_id from $pdo_logs->database.$pdo_logs->table where id=? order by lastplay desc limit 0,?",array($appId,$maxCount));
			if(false === $list){
				$this->_errno =  UCConfApps::APP_ERROR_DB_READ;
				return false;
			//没有记录，则返回空数组
			}elseif(!is_array($list)){ 
				return $list;
			}
		}
    }
	
	//获取有消息用户系统应用的IDs 
	//设置消息用:
    function getAppsUsersSystemHaveMsg($maxCount = 20)
    {
    	//todo:修改成动态可配置的
    	return array(	"2"=>array("appid"=>"2","name"=>"更新头像"),
						"3"=>array("appid"=>"3","name"=>"获取勋章"),
						"6"=>array("appid"=>"6","name"=>"添加好友"),
					);
    }
    //获取有消息用户系统应用的IDs 
	//设置消息用:
    function getAppsUsersOther($maxCount = 20)
    {
    	//
    	$appsother = array_diff($this->arr_all_apps,$this->arr_system_apps);
		if(empty($appsother)){
			return array();	
		}
    	return $appsother;
    }
    
	//获取有消息DEV平台应用的IDs
	//设置消息用:	
	//返回 array(array(id,app_name,app_icon))
    function getAppsAll($maxCount = 200)
    {
		/*
    	$appsother = array_diff($this->arr_all_apps, $this->arr_system_apps);
		if(empty($appsother)){
			return array();	
		}
    	return $appsother;
		*/

		return $this->arr_all_apps;
    }
	
	//构造并返回app的地址
	//
    function genAppUrl($appid)
	{
		$app = $this->getAppInfo($appid);
		return $app['play_url'];
	}
	
	
	//判断好友关系
	//
    function is_friend($userid)
	{
		//判断没有被关注
		$relation = new UCModRelation($this->_user_id);
        return $relation->getSingleRelationType($userid,1);
		
	}



//------------------------------------------------------------------------------------
// 测试环境用
//------------------------------------------------------------------------------------

	function TruncateDB()
	{
		$pdo = UCLibPDOFactory::getPDO('userapps',$this->_user_id,"apps2dbconfig");
		$list  = $pdo->query_with_prepare("delete * from $pdo->database.$pdo->table");
		if(false === $list){
			$this->_errno =  UCConfApps::APP_ERROR_DB_WRITE;
			return false;
		//没有记录，则返回空数组
		}else{ 
			return true;
		}
	}
	
	function TruncateMC()
	{		
		print_r($this->_cache->read('APPS_STORE_SYSTEM_ALL'));
		$this->_cache->write('APPS_STORE_SYSTEM_ALL','');
		$this->_cache->write('APPS_STORE_ALL','');
		$this->_cache->write('APPS_STORE_RECOMMEND','');		
		print_r($this->_cache->read('APPS_STORE_SYSTEM_ALL'));
		return true;
	}
	

	
	
	public static function getInstance(){		
		if(self::$instance == null){		
			self::$instance = new self;
		}
			
		return self::$instance;
	}
	
	
//end
}